﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.Net;
using System.Net.Mail;
using System.IO;
using System.Text;

namespace VSM
{
    public partial class POSearch : System.Web.UI.Page
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        { 
            Response.Cache.SetCacheability(HttpCacheability.Private);
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            scriptManager.RegisterPostBackControl(this.btnExportExcel);
            scriptManager.RegisterPostBackControl(this.btnExportPDF);
           
            if (!IsPostBack)
            {
                LoadData();
               
                    this.btnSendPO.Visible = true;
                    this.btnExportExcel.Visible = true;
                    this.btnExportPDF.Visible = true;
                    this.lblTotal.Text = "0.00";
               
               
            }
        }
        /// <summary>
        /// 
        /// </summary>
       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            Search();
            Timer1.Enabled = false;
        }
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkPONo_Click(object sender, EventArgs e)
        {
           
        }
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkSO_Click(object sender, EventArgs e)
        {
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName.ToUpper() == "COPY")
                {
                    GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
                    int index = gvr.RowIndex;

                    Label lblStatus = (Label)this.grvSearchResult.Rows[index].FindControl("lblDocStatus");
                    if (lblStatus.Text.ToUpper() == "CLOSE" || lblStatus.Text.ToUpper() == "CANCELED")
                    {
                        ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert(This item does not allow to copy');", true);
                        return;
                    }
                    Label lblDocNum = (Label)this.grvSearchResult.Rows[index].FindControl("lblDocEntry");
                    Response.Redirect("ReceiveGoods.aspx?docEntry=" + lblDocNum.Text.Trim());
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private void LoadData()
        {
            DataTable tbTemp = new DataTable();
            tbTemp.Columns.Add("No");
            tbTemp.Columns.Add("DocNum");
            tbTemp.Columns.Add("DocEntry");
            tbTemp.Columns.Add("DocDate");
            tbTemp.Columns.Add("CardCode");
            tbTemp.Columns.Add("CardName");
            tbTemp.Columns.Add("DocDueDate");
            tbTemp.Columns.Add("DocStatus");
            tbTemp.Columns.Add("DocTotal");
            this.grvSearchResult.DataSource = tbTemp;
            this.grvSearchResult.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                Session["ItemChecked"] = null;
                Search();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private void LoadOrderWareHouse(string company)
        {
            
        }
        /// <summary>
        /// 
        /// </summary>
        private void Search()
        {
            //try
            //{

            //    this.grvSearchResult.DataSource = null;
            //    this.grvSearchResult.DataBind();
            //    this.lblError.Visible = false;
            //    MasterData obj = new MasterData();
            //    DataSet dsUser = obj.GetOnlineUser();
            //    DataSet ds = new DataSet();

            //    //Doc Date
            //    DateTime fromDate = DateTime.Now;
            //    DateTime toDate = DateTime.Now;
            //    if (this.txtDateFrom.Text.Length == 0)
            //    {
            //        fromDate = DateTime.ParseExact("12/12/1900", Utils.AppConstants.DATE, null, System.Globalization.DateTimeStyles.None);
            //    }
            //    else
            //    {
            //        if (!Utils.AppConstants.isDateTime(this.txtDateFrom.Text))
            //        {
            //            this.lblError.Text = "DataTime is incorrect format.";
            //            this.lblError.Visible = true;
            //            return;
            //        }
            //        fromDate = DateTime.ParseExact(this.txtDateFrom.Text, Utils.AppConstants.DATE, null, System.Globalization.DateTimeStyles.None);
            //    }
            //    if (this.txtDateTo.Text.Length == 0)
            //    {
            //        toDate = DateTime.MaxValue.Date;
            //    }
            //    else
            //    {
            //        if (!Utils.AppConstants.isDateTime(this.txtDateTo.Text))
            //        {
            //            this.lblError.Text = "DataTime is incorrect format.";
            //            this.lblError.Visible = true;
            //            return;
            //        }
            //        toDate = DateTime.ParseExact(this.txtDateTo.Text, Utils.AppConstants.DATE, null, System.Globalization.DateTimeStyles.None);
            //    }
            //    //Doc Due Date
            //    DateTime delFromDate = DateTime.Now;
            //    DateTime delToDate = DateTime.Now;
            //    if (this.txtDeliDateFrom.Text.Length == 0)
            //    {
            //        delFromDate = DateTime.ParseExact("12/12/1900", Utils.AppConstants.DATE, null, System.Globalization.DateTimeStyles.None);
            //    }
            //    else
            //    {
            //        if (!Utils.AppConstants.isDateTime(this.txtDeliDateFrom.Text))
            //        {
            //            this.lblError.Text = "DataTime is incorrect format.";
            //            this.lblError.Visible = true;
            //            return;
            //        }
            //        delFromDate = DateTime.ParseExact(this.txtDeliDateFrom.Text, Utils.AppConstants.DATE, null, System.Globalization.DateTimeStyles.None);
            //    }
            //    if (this.txtDeliDateTo.Text.Length == 0)
            //    {
            //        delToDate = DateTime.MaxValue.Date;
            //    }
            //    else
            //    {
            //        if (!Utils.AppConstants.isDateTime(this.txtDeliDateTo.Text))
            //        {
            //            this.lblError.Text = "DataTime is incorrect format.";
            //            this.lblError.Visible = true;
            //            return;
            //        }
            //        delToDate = DateTime.ParseExact(this.txtDeliDateTo.Text, Utils.AppConstants.DATE, null, System.Globalization.DateTimeStyles.None);
            //    }

            //    string company = string.Empty;
            //    company = Session[Utils.AppConstants.CompanyCode].ToString();
            //    if (Session[Suki.Utils.AppConstants.CompanyCode].ToString().ToUpper() == System.Configuration.ConfigurationManager.AppSettings["HoldingDatabase"].ToString().ToUpper())
            //    {
            //        company = ddlCompany.SelectedValue.ToString();
            //    }
            //    decimal grandTotal = 0;
            //    if (company != System.Configuration.ConfigurationManager.AppSettings["HoldingDatabase"].ToString())
            //    {
            //        //string outlet = Session[Utils.AppConstants.OutletCode].ToString();
            //        //if (Session[Utils.AppConstants.IsSupperUser].ToString() == "Y")
            //        //{
            //        //    outlet = this.drpOrderWareHouse.SelectedValue.ToString();
            //        //}
            //        string outlet = this.drpOrderWareHouse.SelectedValue.ToString();
            //        ds = obj.SearchPO(Session[Utils.AppConstants.UserCode].ToString(), Session[Utils.AppConstants.Pwd].ToString(),
            //                            company, fromDate, toDate,
            //                             delFromDate, delToDate, this.txtVendorCode.Text,
            //                             this.ddlStatus.SelectedValue.ToString(), this.txtPONo.Text.Trim(), this.ddlChangeStatus.SelectedValue.ToString(),
            //                             outlet, Session[Utils.AppConstants.IsSupperUser].ToString());
            //        if (ds != null && ds.Tables.Count > 0)
            //        {
            //            DataSet dsContact = obj.GetPeronalContact();
            //            int i = 1;
            //            ds.Tables[0].Columns.Add("No");
            //            DataSet dsNew = ds.Clone();
            //            Dictionary<string, string> dicOutlet = (Dictionary<string, string>)Session[Utils.AppConstants.ListOutlet];
            //            foreach (DataRow r in ds.Tables[0].Rows)
            //            {
            //                if (dsUser != null && dsUser.Tables.Count > 0)
            //                {
            //                    DataRow[] rName = dsUser.Tables[0].Select("Code='" + r["U_AB_UserCode"].ToString() + "'");
            //                    if (rName.Length > 0)
            //                    {
            //                        r["UserName"] = rName[0]["Name"];
            //                    }
            //                }
            //                if (dsContact != null && ds.Tables.Count > 0)
            //                {
            //                    DataRow[] rEmail = dsContact.Tables[0].Select("CardCode='" + r["CardCode"].ToString() + "'");
            //                    if (rEmail.Length > 0)
            //                    {
            //                        r["E_Mail"] = rEmail[0]["E_Maill"];
            //                    }
            //                }
            //                r["U_AB_SentSupplier"] = r["ConvertedToSO"].ToString() != "" ? "Sent to Supplier*" : r["U_AB_SentSupplier"];
            //                r["No"] = i;
            //                i++;
            //                if (Utils.AppConstants.isDouble(r["DocTotal"].ToString()))
            //                {
            //                    grandTotal += decimal.Parse(r["DocTotal"].ToString());
            //                }
            //                if ((dicOutlet.Count > 0 && dicOutlet.ContainsKey(r["U_AB_POWhsCode"].ToString())))
            //                {
            //                    dsNew.Tables[0].ImportRow(r);
            //                }
            //                else
            //                {
            //                    dsNew.Tables[0].ImportRow(r);
            //                }

            //            }
            //            if (Session["PageIndex"] != null)
            //            {
            //                this.grvSearchResult.PageIndex = int.Parse(Session["PageIndex"].ToString());
            //            }
            //            if (dicOutlet.Count > 0)
            //            {
            //                Session["HasData"] = dsNew.Tables[0];
            //                this.grvSearchResult.DataSource = dsNew;
            //            }
            //            else
            //            {
            //                Session["HasData"] = ds.Tables[0];
            //                this.grvSearchResult.DataSource = ds;
            //            }
            //            this.grvSearchResult.DataBind();
                       
            //            this.lblTotal.Text = grandTotal.ToString(Utils.AppConstants.NUMBER_FORMAT);
            //        }
            //        else
            //        {
            //            this.lblError.Text = "System is processing another request. Pls try again later.";
            //            this.lblError.Visible = true;
            //        }
            //    }
            //    if (Session["ItemChecked"] != null)
            //    {
            //        for (int i = 0; i < this.grvSearchResult.Rows.Count; i++)
            //        {
            //            CheckBox checkBox = (CheckBox)this.grvSearchResult.Rows[i].FindControl("chkChild");
            //            LinkButton lnkPONo = (LinkButton)this.grvSearchResult.Rows[i].FindControl("lnkPONo");
            //            Dictionary<string, string> dicCheck = new Dictionary<string, string>();
            //            dicCheck = (Dictionary<string, string>)Session["ItemChecked"];
            //            if (dicCheck.ContainsKey(lnkPONo.Text))
            //            {
            //                checkBox.Checked = true;
            //            }
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    this.lblError.Text = ex.Message;
            //    this.lblError.Visible = true;
            //}
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectVendor":
                            this.txtVendorCode.Text = Session["ChosenVendorCode"] != null ? Session["ChosenVendorCode"].ToString() : "";
                            this.txtVendorName.Text = Session["ChosenVendorName"] != null ? Session["ChosenVendorName"].ToString() : "";
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtVendorCode_TextChanged(object sender, EventArgs e)
        {
            if (this.txtVendorCode.Text.Length == 0)
            {
                this.txtVendorName.Text = "";
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSendPO_Click(object sender, EventArgs e)
        {
           
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="lblDelDate"></param>
        /// <param name="lblDocEntry"></param>
        /// <param name="email"></param>
        private bool ProcessExternalPO(MasterData obj, Label lblDelDate, Label lblDocEntry, string email, string poNo)
        {
            
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            Dictionary<string, string> dicCheck;
            if (Session["ItemChecked"] == null)
            {
                dicCheck = new Dictionary<string, string>();
            }
            else
            {
                dicCheck = (Dictionary<string, string>)Session["ItemChecked"];
            }
            for (int i = 0; i < this.grvSearchResult.Rows.Count; i++)
            {
                CheckBox checkBox = (CheckBox)this.grvSearchResult.Rows[i].FindControl("chkChild");
                LinkButton lnkPONo = (LinkButton)this.grvSearchResult.Rows[i].FindControl("lnkPONo");
                if (checkBox.Checked)
                {
                    if (!dicCheck.ContainsKey(lnkPONo.Text))
                    {
                        dicCheck.Add(lnkPONo.Text, lnkPONo.Text);
                    }
                }
                else
                {
                    if (dicCheck.ContainsKey(lnkPONo.Text))
                    {
                        dicCheck.Remove(lnkPONo.Text);
                    }
                }
            }
            Session["PageIndex"] = e.NewPageIndex;
            Session["ItemChecked"] = dicCheck;
            this.grvSearchResult.PageIndex = e.NewPageIndex;
            Search();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private DataTable CreatedTableExport()
        {
            DataTable tblExport = new DataTable();
            //try
            //{
            //    tblExport.Columns.Add("#");
            //    tblExport.Columns.Add("Issued Date");
            //    tblExport.Columns.Add("Delivery Date");
            //    tblExport.Columns.Add("PO No.");
            //    tblExport.Columns.Add("Supplier Name");
            //    tblExport.Columns.Add("User ID & Name");
            //    tblExport.Columns.Add("Total");
            //    tblExport.Columns.Add("PO.Status");
            //    tblExport.Columns.Add("Status");
            //    DataTable tblReportData = (DataTable)Session["HasData"];
            //    if (tblReportData != null)
            //    {
            //        foreach (DataRow r in tblReportData.Rows)
            //        {
            //            DataRow row = tblExport.NewRow();
            //            row[0] = r["No"];
            //            row[1] = DateTime.Parse(r["DocDate"].ToString()).ToString(Utils.AppConstants.DATE);
            //            row[2] = DateTime.Parse(r["DocDueDate"].ToString()).ToString(Utils.AppConstants.DATE);
            //            row[3] = r["DocNum"];
            //            row[4] = r["CardName"];
            //            row[5] = r["U_AB_UserCode"] + "-" + r["UserName"];
            //            row[6] = decimal.Parse(r["DocTotal"].ToString()).ToString(Utils.AppConstants.NUMBER_FORMAT);
            //            row[7] = r["DocStatus"];
            //            row[8] = r["U_AB_SentSupplier"];
            //            tblExport.Rows.Add(row);
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    this.lblError.Text = ex.Message;
            //    this.lblError.Visible = true;
            //}
            return tblExport;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            //using (var exporter = new NpoiExport())
            //{
            //    if (Session["HasData"] != null && ((DataTable)Session["HasData"]).Rows.Count > 0)
            //    {
            //        try
            //        {
            //            string excelFileName = System.Configuration.ConfigurationManager.AppSettings["ExcelFileName"].ToString();
            //            DataTable tblExport = CreatedTableExport();
            //            exporter.ExportDataTableToWorkbook(tblExport, excelFileName);
            //            string saveAsFileName = string.Format(excelFileName + "_{0:d}.xls", DateTime.Now.Ticks);
            //            Response.ClearContent();
            //            Response.ClearHeaders();
            //            Response.ContentType = "application/vnd.ms-excel";
            //            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
            //            Response.Clear();
            //            Response.BinaryWrite(exporter.GetBytes());
            //            Response.End();
            //        }
            //        catch (Exception ex)
            //        {
            //            this.lblError.Text = ex.Message;
            //            this.lblError.Visible = true;
            //        }
            //    }
            //}
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExportPDF_Click(object sender, EventArgs e)
        {
            //string directory = Server.MapPath("TEMP") + "/PDF/";
            //try
            //{
            //    if (Directory.Exists(directory))
            //    {
            //        Directory.Delete(directory, true);
            //    }
            //    if (Session["HasData"] != null && ((DataTable)Session["HasData"]).Rows.Count > 0)
            //    {

            //        string fileName = string.Format("{0}_{1}", System.Configuration.ConfigurationManager.AppSettings["PDFFileName"].ToString(), DateTime.Now.Ticks);
            //        if (!Directory.Exists(directory))
            //        {
            //            Directory.CreateDirectory(directory);
            //        }
            //        string pdfFileName = string.Format("{0}{1}.pdf", directory, fileName);
            //        DataTable tblExport = CreatedTableExport();
            //        float[] relativeWidths = { 20, 50, 50, 50, 200, 100, 50, 50, 70 };
            //        PdfExport.DataSourceToPdf(tblExport, pdfFileName, relativeWidths);
            //        Response.ClearContent();
            //        Response.ClearHeaders();
            //        Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", string.Format("{0}.{1}", fileName, "pdf")));
            //        Response.ContentType = "application/pdf";
            //        Response.Clear();
            //        Response.WriteFile(pdfFileName);
            //        Response.End();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    this.lblError.Text = ex.Message;
            //    this.lblError.Visible = true;
            //}
        }
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSelectVendor_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    string companyCode = Session[Utils.AppConstants.CompanyCode].ToString();
            //    if (Session[Utils.AppConstants.IsSupperUser].ToString().ToUpper() == "Y" && Session[Suki.Utils.AppConstants.CompanyCode].ToString().ToUpper() == System.Configuration.ConfigurationManager.AppSettings["HoldingDatabase"].ToString().ToUpper())
            //    {
            //        companyCode = this.ddlCompany.SelectedValue.ToString();
            //    }
            //    string popup = "OpenVendor('" + companyCode + "','" + string.Empty + "')";
            //    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", popup, true);
            //}
            //catch (Exception ex)
            //{
            //    this.lblError.Text = ex.Message;
            //    this.lblError.Visible = true;
            //}
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.grvSearchResult.DataSource = null;
            this.grvSearchResult.DataBind();
            this.lblTotal.Text = "0.00";
            LoadOrderWareHouse(this.ddlCompany.SelectedValue.ToString());
        }
    }
}